import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { message } from 'antd';
import { Ref, useRef, useState } from 'react';
import { PersonalCenterAPI } from '../common/type';
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css'; // 引入Cropper对应的css
import { getBaseUrl } from '@/services/urlconst';
import { getTenant, getUserID } from '@/utils';

import reqwest from 'reqwest';

export const CropperModal: React.FC<PersonalCenterAPI.ICropperModal> = ({
  onClose,
  visible,
  cropperSrc,
  fileName,
  selectedImageFile,
  userInfoObj,
  uploadReload,
}) => {
  // const prefixCls = 'centerview-';

  const chanageImageRef: Ref<IOneModalRef> = useRef(null); //弹框的ref

  const [uploadLoading, setUploadLoading] = useState<boolean>(false);

  // let cropperRef: any //右侧表单ref
  const cropperRef = useRef<HTMLImageElement>(null);

  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (chanageImageRef) {
      if (chanageImageRef.current) {
        if (chanageImageRef.current.onModalCancel) {
          chanageImageRef.current.onModalCancel();
        }
      }
    }
  };

  /**
   * 保存
   */
  const imageOnOk = () => {
    setUploadLoading(true);

    if (cropperSrc == null) {
      message.error('请选择图片！');
      return false;
    }

    /**
     * 获取图片 对象
     */
    const imageElement: any = cropperRef?.current;
    const cropper: any = imageElement?.cropper;
    const croppedCanvas = cropper?.getCroppedCanvas({
      minWidth: 200,
      minHeight: 200,
      width: 200,
      height: 200,
      maxWidth: 200,
      maxHeight: 200,
    });
    if (typeof croppedCanvas === 'undefined') {
      return;
    }

    croppedCanvas.toBlob(async (blob: any) => {
      // 图片name添加到blob对象里
      blob.name = fileName;
      // 创建提交表单数据对象
      const filedata = new FormData();
      // 添加要上传的文件
      selectedImageFile.forEach((file: any) => {
        filedata.append('uploadImage', file);
      });
      // filedata.append('uploadImage', blob, blob.name);
      const baseUrl = getBaseUrl();

      reqwest({
        url: baseUrl + '/commonController/uploadImage',
        method: 'POST',
        headers: {
          tenantName: getTenant(),
        },
        processData: false,
        data: filedata,
        success: (resp: any) => {
          if (resp.state == 'SUCCESS') {
            message.success('文件上传成功！');
            let imagePayload: any = {
              imageUrl: resp.url,
              id: getUserID(),
              versionNum: userInfoObj?.versionNum,
            };
            // self.modifyImage(url)
            // self.changeImageUrl(resp.url);
            // self.hideModelHandler();
            // self.setState({
            //   isShowUpPic: true,
            //   editImageModalVisible: false,
            // })
            uploadReload();
            setUploadLoading(false);
          } else {
            message.error('文件上传出错！');
            // self.hideModelHandler();
          }
        },
        error: (err: any) => {
          // this.setState({ uploading: false });
          message.error('文件上传失败！');
          setUploadLoading(false);
          // self.hideModelHandler();
        },
      });
    }, 'image/jpg,image/png');
  };
  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={chanageImageRef}
        title={'修改头像'}
        width={document.body.clientWidth * 0.35}
        onCancel={onClose}
        bodyStyle={{
          padding: '15px 20px',
        }}
        centered
        onOk={imageOnOk}
        confirmLoading={uploadLoading}
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <div style={{ width: '70%' }}>
            {/* 参考  https://developer.aliyun.com/article/823128 */}
            <Cropper
              src={cropperSrc} // 原始图片路径
              className="company-logo-cropper"
              ref={cropperRef} // 获取裁剪组件实例
              // crop={onCrop}
              // Cropper.js options
              style={{
                width: document.body.clientWidth * 0.2,
                height: '280px',
              }}
              viewMode={1}
              // zoomable={false}
              initialAspectRatio={9 / 9} //定义裁剪框的初始纵横比。默认情况下，它与画布（图像包装器）的纵横比相同。
              guides={false} //是否显示裁剪框网格
              preview=".cropper_preview"
              rotatable={true} // 启用旋转
              autoCropArea={1 / 2} // 默认裁剪框与画布比例
              checkOrientation={true} // 是否启用检查方向
            />
          </div>
          <div
            className={'cropper_preview'}
            style={{
              width: document.body.clientWidth * 0.1,
              height: document.body.clientWidth * 0.1,
              overflow: 'hidden',
              border: '3px solid rgb(196, 196, 196)',
              borderRadius: '50%',
            }}
          ></div>
        </div>
      </OneModal>
    </>
  );
};
